import texttable

import sqlite3
import argparse
import time
import os.path
import hashlib

class todo():
    def __init__(self,path=False):
        if path:
            if os.path.isfile(path):
                self.sql=sqlite3.connect(path)
                self.cur=self.sql.cursor()
            else:
                self.sql=sqlite3.connect(path)
                self.cur=self.sql.cursor()
                self.cur.execute('create table event(event char(100), date char(10), time char(8),id char(50) primary key,lable char(10))')
                self.cur.execute('create table done(event char(100), date char(10), time char(8),id char(50) primary key,lable char(10))')
                print('created database',path)
        else:
            user_home = os.path.expanduser("~")
            path=user_home+'/.todo.db'
            if os.path.isfile(path):
                self.sql=sqlite3.connect(path)
                self.cur=self.sql.cursor()
            else:
                self.sql=sqlite3.connect(path)
                self.cur=self.sql.cursor()
                self.cur.execute('create table event(event char(100), date char(10), time char(8),id char(50) primary key,lable char(10))')
                self.cur.execute('create table done(event char(100), date char(10), time char(8),id char(50) primary key,lable char(10))')
                print('created database',path)
                
    def add(self,event,date,time):
        id_=hashlib.md5((event+date+time).encode('utf-8')).hexdigest()
        try:
            self.cur.execute('insert into event values(?,?,?,?,?)',(event,date,time,id_,'🞎'))
            self.sql.commit()
            print('add "',event,'" success')
        except:
            print('add error')
            
    def complete(self,id):
        self.cur.execute('select * from event where id like ? limit 1',(id+'%',))
        s=self.cur.fetchall()
        if s==[]:
            print('there is no id like:',id)
            return 0;
        else:
            self.pt(*s)
        s=s[0]
        ss=input('completed? (Yy/Nn) ')
        if ss=='Y':
            self.cur.execute('delete from event where id=?',(s[3],))
            s=list(s)
            s[4]='🞔'
            self.cur.execute('insert into done values(?,?,?,?,?)',s)
        elif ss=='y':
            self.cur.execute('delete from event where id=?',(s[3],))
            s=list(s)
            s[4]='🞔'
            self.cur.execute('insert into done values(?,?,?,?,?)',s)
        self.sql.commit()
        
    def remove(self,id):
        self.cur.execute('select * from event where id like ? limit 1',(id+'%',))
        s=self.cur.fetchall()
        if s==[]:
            self.cur.execute('select * from done where id like ? limit 1',(id+'%',))
            s=self.cur.fetchall()
            if s==[]:
                print('there is no id like:',id)
                return 0;
            else:
                self.pt(*s)
            s=s[0]
            print(s)
            ss=input('delete? (Yy/Nn) ')
            if ss=='Y':
                self.cur.execute('delete from done where id=?',(s[3],))
            elif ss=='y':
                self.cur.execute('delete from done where id=?',(s[3],))
        else:
            if s==[]:
                return 0;
            else:
                self.pt(*s)
            s=s[0]
            ss=input('delete? (Yy/Nn) ')
            if ss=='Y':
                self.cur.execute('delete from event where id=?',(s[3],))
            elif ss=='y':
                self.cur.execute('delete from event where id=?',(s[3],))
        self.sql.commit()
        
    def list_(self,d):
        if d=='0':
            print('events list')
            self.cur.execute('select * from event')
            s=self.cur.fetchall()
            self.pt(*s)
        else:
            print('events list')
            self.cur.execute('select * from event limit '+str(d))
            s=self.cur.fetchall()
            self.pt(*s)
            
    def listc(self,d):
        if d=='0':
            print('completed list')
            self.cur.execute('select * from done')
            s=self.cur.fetchall()
            self.pt(*s)
        else:
            print('completed list')
            self.cur.execute('select * from done limit '+str(d))
            s=self.cur.fetchall()
            self.pt(*s)
            
    def pt(*s):
        #指针传数组
        table = texttable.Texttable()
        table.set_cols_align(["c", "c", "c","c","c"])
        ss=[("event", "date", "time","id","🞐")]
        ss.extend(s[1:]) #合并数组
        #s[0]=<__main__.todo object at 0x7f893f00bda0> 估计是指针的问题
        table.add_rows(ss)
        print(table.draw())


def main():
    parser = argparse.ArgumentParser(description='todo list manager')
    parser.add_argument('-a','--add',help='add a event')
    parser.add_argument('-c','--complete',help='complete a event')
    parser.add_argument('-r','--remove',help='remove a event')
    parser.add_argument('-l','--list',help='list events',nargs='?',const='0')
    parser.add_argument('-lc','--listcomplete',help='list events completed',nargs='?',const='0')
    parser.add_argument('-e','--event',help='event , only need by add')
    parser.add_argument('-d','--date',help='date, only need by add, YYYY-MM-DD')
    parser.add_argument('-t','--time',help='time, only need by add, hh:mm')
    parser.add_argument('-p','--path',help='database path')

    args = parser.parse_args()
    #print(args)
    
    if args.path:
        td=todo(args.path)
    else:
        td=todo()
    
    if args.add:
        if args.event:
            if args.date:
                if args.time:
                    td.add(args.event,args.date,args.time)
                else:
                    td.add(args.event,args.date,str(time.strftime("%H:%M", time.localtime())))
            else:
                td.add(args.event,str(time.strftime("%Y-%m-%d", time.localtime())),str(time.strftime("%H:%M", time.localtime())))
        else:
            if args.date:
                if args.time:
                    td.add(args.add,args.date,args.time)
                else:
                    td.add(args.add,args.date,str(time.strftime("%H:%M", time.localtime())))
            else:
                td.add(args.add,str(time.strftime("%Y-%m-%d", time.localtime())),str(time.strftime("%H:%M", time.localtime())))
    elif args.complete:
        td.complete(args.complete)
    elif args.remove:
        td.remove(args.remove)
    elif args.list:
        td.list_(args.list)
    elif args.listcomplete:
        td.listc(args.listcomplete)
    else:
        print('    need an action\n    use -h, --help to show this help message')
        
if __name__=='__main__':
    main()
